package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-04-28
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductDetailsMapper productDetailsMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private SkuStockMapper skuStockMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<Product> getProductListPage() {

        return productMapper.getProductListPage();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveProduct(Product product) {
        //保存新增商品spu信息
        //设置新增商品状态:未上架
        product.setStatus(0);
        //设置商品的配置人
        product.setCreateBy(SecurityUtils.getUsername());
        //保存商品spu信息
        baseMapper.insert(product);
        //获取商品id为添加其他商品关联表信息提供条件
        Long productId = product.getId();
        //添加商品详情信息
        //构建商品相信信息构建器
        ProductDetails productDetails = new ProductDetails();
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        if(!Collections.isEmpty(detailsImageUrlList)){
            //将集合中的数据用逗号隔开合并成一个字符串
            String url = String.join(",", detailsImageUrlList);
            productDetails.setImageUrls(url);
        }
        //关联商品id
        productDetails.setProductId(productId);
        //设置创建人姓名
        productDetails.setCreateBy(SecurityUtils.getUsername());
        productDetailsMapper.insert(productDetails);
        //保存商品SKU信息
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (!Collections.isEmpty(productSkuList)){
            int num=0;
            for (ProductSku productSku : productSkuList) {
                //设置商品编码
                productSku.setSkuCode(productId+"_"+num++);
                //设置商品名字
                productSku.setSkuName(product.getName()+" "+productSku.getSkuSpec());
                //关联商品id
                productSku.setProductId(productId);
                //摄者初始状态
                productSku.setStatus(0);
                //设置创建人姓名
                productSku.setCreateBy(SecurityUtils.getUsername());
                //保存商品sku信息
                productSkuMapper.insert(productSku);
                //获取商品skuId
                Long skuId = productSku.getId();

                //保存商品sku库存
                SkuStock skuStock = new SkuStock();
                skuStock.setStatus(0);
                //关联skuId
                skuStock.setSkuId(skuId);
                //设置总库存数
                skuStock.setTotalNum(productSku.getStockNum());
                //设置锁定库存数
                skuStock.setLockNum(0);
                //设置可用库存数
                skuStock.setAvailableNum(productSku.getStockNum());
                //设置销量
                skuStock.setSaleNum(0);
                //设置创建人姓名
                skuStock.setCreateBy(SecurityUtils.getUsername());
                //保存商品SKU库存信息
                skuStockMapper.insert(skuStock);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long id, Integer status) {
        //修改商品spu状态
        Product product = new Product();
        product.setId(id);
        product.setStatus(status);
        product.setUpdateBy(SecurityUtils.getUsername());
        productMapper.updateById(product);
        //修改商品SKU状态
        LambdaUpdateWrapper<ProductSku> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProductSku::getProductId,id);
        updateWrapper.set(ProductSku::getStatus,status);
        productSkuMapper.update(null,updateWrapper);
        //查询商品库存的skuId
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductSku::getProductId,id);
        wrapper.select(ProductSku::getId);
        List<Long> skuIdList = productSkuMapper
                .selectList(wrapper)
                .stream()
                .map(ProductSku::getId)
                .collect(Collectors.toList());
        //修改商品sku库存状态
        LambdaUpdateWrapper<SkuStock> stockWrapper = new LambdaUpdateWrapper<>();
        stockWrapper.in(SkuStock::getSkuId,skuIdList);
        stockWrapper.set(SkuStock::getStatus,status);
        skuStockMapper.update(null,stockWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProductById(List<Long> ids) {
        //删除商品sku表
        baseMapper.deleteBatchIds(ids);
        //查询关联id
        LambdaQueryWrapper<ProductSku> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ProductSku::getProductId,ids);
        wrapper.select(ProductSku::getId);
        List<ProductSku> productSkus = productSkuMapper.selectList(wrapper);
        if(!Collections.isEmpty(productSkus)){
            List<Long> collect = productSkus
                    .stream()
                    .map(ProductSku::getId)
                    .collect(Collectors.toList());
            //删除商品sku表
            productSkuMapper.deleteBatchIds(collect);
            //删除商品sku库存表
            LambdaQueryWrapper<SkuStock> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SkuStock::getSkuId,collect);
            skuStockMapper.delete(queryWrapper);
        }
        //删除商品详情表
        LambdaQueryWrapper<ProductDetails> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(ProductDetails::getProductId,ids);
        productDetailsMapper.delete(lambdaQueryWrapper);
        //修改商品状态,如果是上架就加入到位图中,如果是下架就从位图中移除
        //设置存在位图中数据的key
        String key = "product:sku:data";
        productSkus.forEach(productSku -> {
            if(productSku.getStatus()==1){
                redisTemplate.opsForValue().setBit(key,productSku.getId(),true);
            } else if (productSku.getStatus()==-1) {
                redisTemplate.opsForValue().setBit(key,productSku.getId(),false);
            }
        });
    }
}
